/**
 * 
 */
package co.fitstart.admin.web.controller.system;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.principal.Principal;

/**
 * 
 * @author Leo
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-system")
public class ProfileController {
    
    private static Logger logger = LoggerFactory.getLogger(ProfileController.class);
    
    @Autowired
    private PrincipalService principalService;

    /**
     * Principal profile page
     * 
     * @param id
     * @return
     */
    @RequestMapping("/profile")
    @MenuSetting("submenu-profile-management")
    public ModelAndView profile(@Secure(property = "id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/profile/profile-view");
        
        Principal principal = principalService.get(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        Date latestUpdateTime = principal.getLatestUpdateTime();
        
        int restDay = 6;
        
        if(latestUpdateTime != null) {
            Date expiryTime = DateUtils.addDays(latestUpdateTime, 28);
            
            long time = expiryTime.getTime() - (new Date()).getTime();
            
            if(time <= 0) {
                restDay = -1;
            } else {
                restDay = (int)(time/1000/60/60/24);
            }
        }
        
        modelAndView.addObject("restDay", restDay);
        
        return modelAndView;
        
    }
    
    /**
     * Prepare to change password
     * 
     * @param id
     * @return
     */
    @RequestMapping("/profile/change-password")
    public ModelAndView changePassword(@Secure(property = "id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/profile/change-password");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
    }
    
    @RequestMapping("/profile/change-password-needed")
    public ModelAndView changePasswordNeeded(@Secure(property = "id") Long id) {
        
        Principal principal = principalService.load(Principal.class, id);
        
        if(principal.getLatestUpdateTime() == null || DateUtils.addDays(principal.getLatestUpdateTime(), 28).after(new Date())) {
            return new ModelAndView("redirect:/home");
        }
        
        ModelAndView modelAndView = new ModelAndView("system/profile/change-password-needed");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
    }

    /**
     * Do change password
     * 
     * @param id
     * @param password
     * @return
     */
    @RequestMapping(value = "/profile/change-password", method = RequestMethod.PATCH)
    public @ResponseBody String onChangePassword(@Secure(property = "id") Long id, @RequestParam("password") String password) {
        
        Result result = new Result();
        
        try {
            
            Principal principal = principalService.load(Principal.class, id);
            principalService.changePassword(principal, password);
            
            result.success().message("修改密码成功！");
        } catch (BusinessException e) {
            result.fail().message(e.getMessage());
        } catch (Exception e) {
            
            result.fail().message("修改密码失败，请稍后再试！");
            
            logger.error("onChangePassword() error", e);
            
        }
            
        return JsonUtils.toJsonString(result);
        
    }
    
}
